<template>
    <el-dialog :title="title" v-model="dialogVisible" width="700px" destroy-on-close @close="handleClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色编码" prop="code">
                <el-input v-model="form.code" placeholder="请输入角色编码" />
            </el-form-item>
            <el-form-item label="状态">
                <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
            <el-form-item label="菜单权限">
                <el-scrollbar height="300px" class="tree-container">
                    <el-tree 
                        ref="menuTreeRef" 
                        :data="menuOptions" 
                        show-checkbox 
                        node-key="menu_id"
                        default-expand-all
                        :props="{
                            label: (data: any) => data.title || data.name || '未命名菜单',
                            children: 'children'
                        }" 
                        :default-checked-keys="form.menu_ids" 
                    />
                </el-scrollbar>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type { FormInstance, ElTree } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createRole, updateRole } from '/@/api/role'
import { getMenuList } from '/@/api/menu'
import type { RoleForm } from '/@/api/role'

const props = defineProps<{
    visible: boolean
    type: 'add' | 'edit'
    currentRow?: any
}>()

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = computed({
    get: () => props.visible,
    set: (val) => emit('update:visible', val)
})

const title = computed(() => props.type === 'add' ? '新增角色' : '编辑角色')

const formRef = ref<FormInstance>()
const menuTreeRef = ref<InstanceType<typeof ElTree>>()
const menuOptions = ref([])

const defaultForm: RoleForm = {
    name: '',
    code: '',
    status: 1,
    remark: '',
    menu_ids: [],
}

const form = reactive<RoleForm>({ ...defaultForm })

const rules = {
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
}

// 获取菜单列表
const fetchMenuList = async () => {
    try {
        const { data } = await getMenuList()
        menuOptions.value = data
    } catch (error) {
        console.error('获取菜单列表失败:', error)
    }
}

// 初始化表单数据
const initFormData = () => {
    if (props.type === 'edit' && props.currentRow) {
        Object.assign(form, props.currentRow)
        form.menu_ids = Array.isArray(form.menu_ids) ? form.menu_ids : []
    } else {
        Object.assign(form, defaultForm)
    }
}

// 处理提交
const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 获取选中的菜单ID
                form.menu_ids = menuTreeRef.value?.getCheckedKeys(false) as number[]

                if (props.type === 'add') {
                    await createRole(form)
                    ElMessage.success('新增成功')
                } else {
                    await updateRole(form)
                    ElMessage.success('更新成功')
                }
                emit('success')
                handleClose()
            } catch (error) {
                console.error('提交失败:', error)
            }
        }
    })
}

// 处理关闭
const handleClose = () => {
    dialogVisible.value = false
    formRef.value?.resetFields()
}

// 监听visible变化
watch(() => props.visible, (val) => {
    if (val) {
        initFormData()
        fetchMenuList()
    }
})
</script>

<style lang="scss" scoped>
.tree-container {
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    width: 100%;
}
</style>